import React from 'react';
import { connect } from 'dva'

import moment from 'moment'
import Title from 'components/Title'
import Chart from 'components/Chart'

import Tools from 'utils/tools';

import { config } from 'utils'
const { scada } = config;
const {
  IntervalMonth,
  DdToken
} = scada;

@connect(({ business }) => ({ ...business }))
class StatisticsBar extends React.Component {
  echartsConf = [
    {
      key: 'sumYearPay',
      label: '收费分析',
      dataFields: ['totalAmount', 'paidAmount'],
      zoom: 10000,
      chart: {
        type: 'Common2', dataSource: 'sumYearPayResource',
        columns: {
          seriesItems: [
            { name: '水费回收率', field: 'radio', type: 'line', yAxisIndex: 1 },
            { name: '应收水费', field: 'supply', type: 'bar', barWidth:'25%' },
            { name: '已收水费', field: 'sell', type: 'bar', barWidth:'25%' },
            { name: '欠费金额', field: 'subtract', type: 'bar', barWidth:'25%' },
          ],
          xAxis: { field: 'billDate', format: 'M月' },
          yAxis: [{ name: '元' }, { name: '%'}],
        },
        color: ['251, 212, 55', '68, 130, 255', '78, 203, 115', '134, 147, 243'],
        other: { showLegend: true },
      },
      server: { type: 'business/querySumYearPay', payload: { } },
    },
    {
      key: 'cbqk',
      label: '抄表情况分析',
      dataFields: ['all', 'succ'],
      chart: {
        type: 'Common2', dataSource: 'DivisionCopyrateResourceStatistics',
        columns: {
          seriesItems: [
            { name: '抄表块数', field: 'sell', type: 'bar' },
            { name: '未抄表块数', field: 'subtract', type: 'bar' },
            { name: '水表抄见率', field: 'radio', type: 'line', yAxisIndex: 1 },
          ],
          yAxis: [{ name: '块' }, { name: '%'}],
        },
        color: ['251, 212, 55', '68, 130, 255', '78, 203, 115', '134, 147, 243'],
        other: { showLegend: true },
      },
      server: { type: 'business/queryDivisionCopyrate', payload: { type: 'Statistics', Token: DdToken, interval: IntervalMonth, dvs: [] } },
    },
  ]

  constructor(props) {
    super(props);

    let time;
    if ('defaultValue' in props) {
      time = props.defaultValue;
    }
    this.state = {
      time,
      monthList: []
    };
  }

  componentWillMount(){
    this.init()
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.defaultValue !== nextProps.defaultValue) {
      if (nextProps.defaultValue) {
        this.setState({
          time: nextProps.defaultValue
        }, () => {
          this.init()
        })
      }
    }
  }

  init = () => {
    this.setDateECharts()
    this.setDateMonthList()
  }

  setDateMonthList = () => {
    const { time } = this.state;
    const monthList = Tools.getFullMonth(time)
    this.setState({
      monthList
    })
  }

  // 图表
  setDateECharts = () => {
    const { echartsConf } = this;
    echartsConf.forEach(ele => {
      const { server } = ele;
      if (server) this.queryECharts(server);
    })
  }
  // 处理echarts配置请求
  queryECharts = async (server) => {
    const { time: year } = this.state;
    let { payload, type } = server;

    if(type === 'business/querySumYearPay'){
      Object.assign(payload, {
        year,
      })
    }else{
      Object.assign(payload, {
        // 获取时间戳(以秒为单位)
        begin: moment(moment(`${year}-01`).startOf('month')).unix(),
        end: moment(moment(`${year}-12`).endOf('month')).unix(),
      })
    }
    
    Object.assign(server, { payload })
    await this.props.dispatch(server);
  }

  // 调用营收接口，金额 金额，需要除以10000（数据库是存整数型的，放大一万倍精度，所以要除以10000才是元）
  /**
   * 产销情况分析
   * 逻辑：通过区间过滤出所需要结果
   */
  getDate = (dataSource, monthList, fields = ['waterSupply', 'waterSell'], fieldList = [{ field: 'supply', name: '供水量'}, { field: 'sell', name: '售水量' }, { field: 'subtract', name: '产销差' }, { field: 'radio', name: '产销差率' }], xField = 'time', zoom = 1) => {
    // 获取某月的第一天 和 最后一天
    let resource = {}
    let time = []
    
    let supply = [],
        sell = [],
        subtract = [],
        radio = [];

    monthList.forEach(ele => {
      // 每月第一天 和 最后一天
      const startTimestamp = moment(moment(ele).startOf('month')).unix();
      const endTimestamp = moment(moment(ele).endOf('month')).unix();
      
      const supplyData = Tools.SumRange(dataSource, fields[0], [startTimestamp, endTimestamp], xField)
      const sellData = Tools.SumRange(dataSource, fields[1], [startTimestamp, endTimestamp], xField)
      
      const subtractData = supplyData - sellData;  // 相差
      const radioData = supplyData === 0 ? 0 : (sellData/supplyData * 100).toFixed(2) * 1; // 相差率

      // 处理时间
      time.push(moment(ele).format('M月'))
      // 处理值
      supply.push(supplyData/zoom)
      sell.push(sellData/zoom)
      subtract.push(subtractData/zoom) // Fix: 注意 javascript精度丢失
      radio.push(radioData)
    })
    
    fieldList.forEach(ele => {
      const { field } = ele;
      Object.assign(ele, { data: eval(field)})
    })
        
    Object.assign(resource, { time, data: fieldList })
    return resource
  }

  // 图表渲染
  render() {
    const { props, state, echartsConf } = this;
    const { monthList } = state;

    let charts = null;
    charts = echartsConf.map(ele => {
      const { key, label, dataFields, chart, extra } = ele;
      const { type: chartType, dataSource, columns, color, other } = chart;

      
      const xField = columns.xAxis && columns.xAxis.field ? columns.xAxis.field : 'time'
      const zoom = ele.zoom ? ele.zoom : 1;

      // 手动处理数据返回结果
      const timeList = props[dataSource] && props[dataSource].timeList ? props[dataSource].timeList : props[dataSource];
      let Resource = this.getDate(timeList, monthList, dataFields, columns['seriesItems'], xField, zoom);
      return (<Title key={key} title={label}>
          <Chart
            type={chartType}
            color={color}
            columns={columns}
            dataSource={Resource}
            extra={extra}
            other={other}
          />
        </Title>)
    })
    return <>{charts}</>
  }
}

export default StatisticsBar;
